//
//  MJTabBar.m
//  00-ItcastLottery
//
//  Created by apple on 14-4-14.
//  Copyright (c) 2014年 itcast. All rights reserved.
//

/**
 
 *  随机颜色
 
 */

#define RandomColor [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1]



#import "ZHTabBar.h"
#import "ZHTabBarButton.h"

@interface ZHTabBar()
/**
 *  记录当前选中的按钮
 */
@property (nonatomic, weak) ZHTabBarButton *selectedButton;
@end

@implementation ZHTabBar

/**
 *  用来添加内部的按钮个数
 *
 *  @param name    按钮图片的名称
 *  @param selName 选中时候按钮的图片名称
 */
- (void)addTabButtonWithName:(NSString *)name selName:(NSString *)selName {
    
    // 创建按钮
    ZHTabBarButton *button = [ZHTabBarButton buttonWithType:UIButtonTypeCustom];
    // 设置图片
    [button setBackgroundImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:selName] forState:UIControlStateSelected];
    [self addSubview:button];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    if (self.subviews.count == 1) {
        [self buttonClick:button];
    }
    button.backgroundColor = RandomColor;
}

/**
 *  初始化按钮
 */

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    NSInteger count = self.subviews.count;
    
    for (int i = 0; i<count; i++) {
        ZHTabBarButton *button = self.subviews[i];
        
        // 设置frame
        CGFloat buttonY = 0;
        CGFloat buttonW = self.frame.size.width / count;
        CGFloat buttonH = self.frame.size.height;
        CGFloat buttonX = i * buttonW;
        button.tag = i;
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
    }
}

/**
 *  监听按钮点击
 */
- (void)buttonClick:(ZHTabBarButton *)button
{
    // 0.通知代理
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectButtonFrom:to:)]) {
        [self.delegate tabBar:self didSelectButtonFrom:self.selectedButton.tag to:button.tag];
    }
    
    // 1.让当前选中的按钮取消选中
    self.selectedButton.selected = NO;
    
    // 2.让新点击的按钮选中
    button.selected = YES;
    
    // 3.新点击的按钮就成为了"当前选中的按钮"
    self.selectedButton = button;
}
@end